import "./upload.css";

import React, { useState, useEffect, Fragment, useCallback } from "react";
import { Upload, message, Button, Table, Modal, Image, Spin } from "antd";
import useStore from "../../utils/myStore";

export default function CustomeUpload({ canEdit, callBack }) {
  const [uploadLoading, setUploadLoading] = useState(false);
  const [currentTabName, setCurrentTabName] = useState("");

  const initialFile = {
    form: {
      areaCode: 0, // this.$store.state.user.dataPowerCode,
      type: "0",
    },
    list: {},
    preview: {
      show: false,
      url: "",
    },
  };

  // const {showLoading, hideLoading} = useStore()

  const [file, setFile] = useState(initialFile);

  const [, updateState] = useState();
  const forceUpdate = useCallback(() => updateState({}), []);

  const data = [
    { extra: "0", id: "30", name: "中标通知书" },
    { extra: "1", id: "31", name: "物业服务合同扫描件" },
    { extra: "1", id: "33", name: "负责人证件图片" },
    { extra: "0", id: "34", name: "物业服务合同备案证明" },
    { extra: "", id: "32", name: "负责人培训经历证明" },
  ];
  const setting = {
    name: "file",
    action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
    showUploadList: false,
    onChange(info) {
      if (info.file.status === "uploading") {
        setUploadLoading(true);
        // showLoading(true)

        return true;
      }
      if (info.file.status !== "uploading") {
        console.log(info.file, info.fileList);

        setUploadLoading(false);
        // hideLoading()
      }
      if (info.file.status === "done") {
        message.success(`${info.file.name} 上传成功`);
        console.log(info.file);
        let tmp = file;
        file.list[tmp.form.type].push({ ...info.file, key: info.file.uid });
        setFile(tmp);

        console.log(file);
        setDataSource(file.list[file.form.type]);
        forceUpdate();

        callBack(file.list, checkValid());
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 上传失败.`);
      }
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        message.error("只能上传 JPG/PNG 格式的文件!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error("文件必须小于 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
  };

  const checkValid = () => {
    let result = true;
    data.forEach((item) => {
      if (
        item.extra == 1 &&
        (!file.list[item.id] || file.list[item.id].length == 0)
      ) {
        result = false;
        return;
      }
    });
    return result;
  };

  const [dataSouce, setDataSource] = useState([]);

  // useEffect(()=>{
  //     setDataSource(file.list[file.form.type])
  // },[file])

  // const handleClick=(item) =>{
  //   let tmp = file;
  //   tmp.form.type = item.id;
  //   setFile(tmp)
  //   setCurrentTabName(item.name)
  // }

  useEffect(() => {
    setCurrentTabName(data[0].name);

    let tmp = file;
    tmp.form.type = data[0].id;

    data.forEach((item) => {
      tmp.list[item.id] = [];
    });
    setFile(tmp);

    callBack(tmp.list, checkValid());
  }, []);

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "大小",
      dataIndex: "size",
      key: "size",
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
    },
    {
      title: "操作",
      key: "operation",
      // fixed: "right",
      // width: 100,
      render: (text, record, index) =>
        canEdit ? (
          <Button
            size="small"
            type="primary"
            onClick={() => {
              console.log(text);
              console.log(record);
              console.log(index);

              setFile({
                ...file,
                preview: { show: true, url: record.response.url },
              });
            }}
          >
            预览
          </Button>
        ) : null,
    },
  ];

  return (
    <Fragment>
      <Spin spinning={uploadLoading}>
        <div className="uploadContainer">
          <ul className="filesType">
            {data.map((item) => {
              return (
                <li
                  className={[
                    item.extra == 1 ? "extra" : null,
                    item.id == file.form.type ? "active" : null,
                  ].join(" ")}
                  // className={classnames({
                  //   styles.extra: item.extra == 1,
                  //   active: file.form.type == item.id,
                  // })}
                  key={item.id}
                  onClick={() => {
                    let tmp = file;
                    tmp.form.type = item.id;
                    setFile(tmp);
                    setCurrentTabName(item.name);
                  }}
                >
                  <span>
                    {item.name +
                      "(" +
                      (file.list[item.id] ? file.list[item.id].length : 0) +
                      ")"}
                  </span>
                </li>
              );
            })}
            {/* <li *ngFor="let item of data" [class]="{ 'extra': item.extra == '1' ,'active':file.form.type==item.id}" (click)="file.form.type=item.id;currentTabName = item.name">
      <span>{{item.name+ '('+(file.list[item.id]?file.list[item.id].length:0)+')'}}</span>
    </li> */}
          </ul>
          <div style={{ flex: 1, margin: "8px 0" }}>
            {canEdit ? (
              <Upload {...setting}>
                <Button
                  style={{ marginBottom: "8px" }}
                  // loading={uploadLoading}
                  type="primary"
                >
                  上传{currentTabName}
                </Button>
              </Upload>
            ) : null}
            <Table dataSource={dataSouce} columns={columns}></Table>
            {/* <p-fileUpload name="myfile[]" url="./upload.php" [auto]="true" accept="image/*" [chooseIcon]="''" maxFileSize="1000000" [chooseLabel]="'上传'+currentTabName" mode="basic"></p-fileUpload> */}
          </div>

          <Modal
            title="预览"
            visible={file.preview.show}
            onCancel={() => setFile({ ...file, preview: { show: false } })}
            footer={null}
          >
            <Image
              width={"100%"}
              src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
            />
          </Modal>
        </div>
      </Spin>
    </Fragment>
  );
}
